package com.idata.service.services;


import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Maps;
import com.idata.model.dto.KGProxySearchResultDTO;
import com.idata.model.dto.TagDTO;
import com.idata.model.enums.StatisticsTypeForInputEnum;
import com.idata.model.proxyDO.KGCitizenDO;
import com.idata.model.proxyDO.KGRecommendPersonDO;
import com.idata.model.request.SearchRequest;
import com.idata.model.response.CitizenResponse;
import com.idata.model.response.CitizenSearchResponse;
import com.idata.model.response.DisputeRelationResponse;
import com.idata.model.response.PageResult;
import com.idata.model.response.PhoneInfoResponse;
import com.idata.model.response.TagResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @File AssociationQueryManager.Java
 * @Modify Time      @Author    @Version    @Description
 * ------------      -------    --------    -----------
 * 2023/9/21         yd.j      1.0          关联检索
 */
@Service
public class AssociationQueryManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(AssociationQueryManager.class);

    @Autowired
    private PortaitAnalysisService portaitAnalysisService;

    @Autowired
    private CitizenInfoService citizenInfoService;

    @Autowired
    private TagService tagService;

    /**
     * 根据传入的数据进行匹配
     * @param searchRequest 传入数据
     * @return 返回匹配结果
     */
    public PageResult<CitizenSearchResponse> search(SearchRequest searchRequest) {
        // 搜索到数据
        PageResult<KGProxySearchResultDTO> kgCitizenResponse = citizenInfoService.proxySearchCitizen(
                searchRequest.getContent(), searchRequest.getPageNum(), searchRequest.getPageSize());
        if (kgCitizenResponse.getTotal() == null
                || kgCitizenResponse.getTotal().equals(0L)
                || CollectionUtil.isEmpty(kgCitizenResponse.getList())) {
            return new PageResult<>(null, 0L);
        }

        List<KGProxySearchResultDTO> kgProxySearchResultDTOS = kgCitizenResponse.getList();
        List<KGCitizenDO> kgCitizenDOList = kgProxySearchResultDTOS.stream().map(KGProxySearchResultDTO::getKgCitizenDO).collect(Collectors.toList());
        Map<String, List<TagResponse>> tagsMap = this.getTagMap(kgProxySearchResultDTOS);
        List<String> idCardNumberList = kgCitizenDOList.stream().map(kgcitizen -> kgcitizen.getPeople().getIdCard()).collect(Collectors.toList());
        Map<String, List<DisputeRelationResponse>> kgDisputeRelationMap = portaitAnalysisService.getDisputeRelation(idCardNumberList, StatisticsTypeForInputEnum.SUM.getCode());
        Map<String, List<PhoneInfoResponse>> kgPhoneMap = citizenInfoService.proxyGetPhoneMap(idCardNumberList);

        List<CitizenSearchResponse> citizenSearchResponseList = kgCitizenDOList.stream()
                .map(kgCitizen -> {
                    String idCardNumber = kgCitizen.getPeople().getIdCard();
                    List<DisputeRelationResponse> disputeRelationResponseList = Optional.ofNullable(kgDisputeRelationMap.get(idCardNumber)).orElse(new ArrayList<>())
                            .stream().sorted(Comparator.comparingLong(DisputeRelationResponse::getDisputeTotalCount).reversed()).collect(Collectors.toList());
                    return new CitizenSearchResponse()
                            .setRelationList(disputeRelationResponseList)
                            .setPhoneList(kgPhoneMap.get(idCardNumber))
                            .setTagList(tagsMap.get(idCardNumber))
                            .setCitizenInfo(CitizenResponse.convertFromKGCitizen(kgCitizen));
                })
                .collect(Collectors.toList());
        return new PageResult<>(citizenSearchResponseList, kgCitizenResponse.getTotal());
    }

    public Map<String, List<TagResponse>> getTagMap(List<KGProxySearchResultDTO> kgProxySearchResultDTOS) {
        Map<String, List<TagDTO>> tagsMap = kgProxySearchResultDTOS.stream()
                .collect(Collectors.toMap(dto -> dto.getKgCitizenDO().getPeople().getIdCard(), KGProxySearchResultDTO::getTagDTOS, (old, value) -> value));
        Map<String, List<TagResponse>> tagResponses = Maps.transformValues(tagsMap,
                tagDTOS -> tagDTOS.stream().map(tagDTO -> new TagResponse(tagDTO.getTagValue(), tagService.isHighLight(tagDTO.getTagKey()))).collect(Collectors.toList()));
        return tagResponses;
    }


    public List<CitizenSearchResponse> relatedCitizen(SearchRequest request) {
        // 搜索到数据
        PageResult<KGProxySearchResultDTO> kgCitizenResponse = citizenInfoService.proxySearchCitizen(
                request.getContent(), request.getPageNum(), request.getPageSize());
        if (kgCitizenResponse.getTotal() == null
                || kgCitizenResponse.getTotal().equals(0L)
                || CollectionUtil.isEmpty(kgCitizenResponse.getList())) {
            return new ArrayList<>();
        }
        List<String> queryIdCards = kgCitizenResponse.getList().stream().map(dto -> dto.getKgCitizenDO().getPeople().getIdCard()).collect(Collectors.toList());
        List<KGRecommendPersonDO> relatedCitizenList = queryIdCards.stream().map(citizenInfoService::proxyRelatedCitizen).flatMap(List::stream).collect(Collectors.toList());
        return relatedCitizenList.stream().sorted(Comparator.comparingInt(KGRecommendPersonDO::getDisputeCount).reversed())
                .map(CitizenSearchResponse::convertFromKGRecommendPerson).collect(Collectors.toList());
    }
}
